#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include "LockGuard1.hpp"

using namespace std;

#define NUM 4

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int tickets = 100;

class ThreadDate // 作为线程函数的参数
{
public:
    ThreadDate(int num)
    {
        threadname = "thread-" + to_string(num);
    }

public:
    string threadname;
};

void *getTicket(void *args)
{
    ThreadDate *td = static_cast<ThreadDate *>(args);
    const char *name = td->threadname.c_str();
    while (true)
    {
        {
            // pthread_mutex_lock(&lock);
            LockGuard Lock(&lock);
            if (tickets > 0)
            {
                usleep(1000);
                printf("who=%s, get a ticket: %d\n", name, tickets);
                tickets--;
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
        usleep(13);
    }
    printf("%s ... quit\n", name);
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        ThreadDate *td = new ThreadDate(i);
        pthread_create(&tid, nullptr, getTicket, td); // tid可以得到了
        tids.push_back(tid);
    }

    for (auto tid : tids)
    {
        pthread_join(tid, nullptr);
    }

    return 0;
}